const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
const path = require('path');
const pathSep = require('path').sep;
const fs = require('fs');
const getModuleId = require('./getModulelId').getModuleId;
const pubModuleIds = require('./pubModuleId.json');
/**
 * Metro configuration
 * https://reactnative.dev/docs/metro
 *
 * @type {import('metro-config').MetroConfig}
 */
const config = {
  // transformer: {
  //   splitBundles: async () => ({
  //     baseBundle: {
  //       // 提取公共模块（React Native 框架及常用依赖）
  //       test: (module) =>
  //         module.path.includes("node_modules/react-native") ||
  //         module.path.includes("node_modules/react") ||
  //         module.path.includes("node_modules/react-navigation"),
  //     },
  //     businessBundle: {
  //       // 其他业务逻辑文件
  //       test: (module) => module.path.includes("src/business"),
  //     },
  //   }),
  serializer: {
    createModuleIdFactory: () => {
      const projectRootPath = path.resolve(__dirname);

      return (path) => {
        const name = getModuleId(projectRootPath, path);
        // console.log('name', name, projectRootPath, path);

        const coreModuleIds = require('./coreModuleId.json');
        const pubModuleIds = require('./pubModuleId.json');
        if (!coreModuleIds.includes(name)) {
          console.log('2------', name);
          if (!pubModuleIds.includes(name)) {
            console.log('21------', name);
            pubModuleIds.push(name);
            fs.writeFileSync(
              projectRootPath + pathSep + 'pubModuleId.json',
              JSON.stringify(pubModuleIds)
            );
          }
        } else {
          // console.log(3, name);
        }

        return name;
      };
    },
    processModuleFilter: (module) => {
      const projectRootPath = __dirname;
      const name = getModuleId(projectRootPath, module['path']);

      if (pubModuleIds.includes(name)) {
        return true;
      }
      return false;
    },
  },
};

// console.log("__dirname", path, __dirname, config);
// console.log("moduleArr---", moduleArr);
module.exports = mergeConfig(getDefaultConfig(__dirname), config);
